package com.ruoyi.material.service.impl;

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.material.PurchaseConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.material.domain.FoodType;
import com.ruoyi.material.domain.MaterialSupplier;
import com.ruoyi.material.domain.PurchaseOrder;
import com.ruoyi.material.domain.PurchaseOrderProduct;
import com.ruoyi.material.domain.req.PurchaseOrderAddReq;
import com.ruoyi.material.domain.vo.PurchaseOrderVO;
import com.ruoyi.material.mapper.FoodTypeMapper;
import com.ruoyi.material.mapper.MaterialSupplierMapper;
import com.ruoyi.material.mapper.PurchaseOrderMapper;
import com.ruoyi.material.mapper.PurchaseOrderProductMapper;
import com.ruoyi.material.service.IPurchaseOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 采购单Service业务层处理
 *
 * @author wng
 * @date 2024-08-04
 */
@Service
public class PurchaseOrderServiceImpl implements IPurchaseOrderService {
    @Resource
    private PurchaseOrderMapper purchaseOrderMapper;
    @Resource
    private MaterialSupplierMapper materialSupplierMapper;
    @Resource
    private FoodTypeMapper foodTypeMapper;
    @Resource
    private PurchaseOrderProductMapper purchaseOrderProductMapper;

    /**
     * 查询采购单
     *
     * @param id 采购单主键
     * @return 采购单
     */
    @Override
    public PurchaseOrderVO selectPurchaseOrderById(Long id) {
        PurchaseOrder purchaseOrder = purchaseOrderMapper.selectPurchaseOrderById(id);
        if (purchaseOrder == null) {
            throw new ServiceException("未查询到采购单");
        }
        PurchaseOrderVO vo = convertPurchaseOrder(purchaseOrder);
        //相关物品
        List<PurchaseOrderProduct> products = purchaseOrderProductMapper.selectPurchaseOrderProductList(new PurchaseOrderProduct() {{
            setOrderId(vo.getId());
        }});
        products.forEach(item -> {
            FoodType foodType = foodTypeMapper.selectFoodTypeById(item.getfTypeSub());
            if (foodType != null) {
                item.getParams().put("fTypeSubName", foodType.getTypeName());
            }
        });
        vo.getParams().put("products", products);
        return vo;
    }

    /**
     * 查询采购单列表
     *
     * @param purchaseOrder 采购单
     * @return 采购单
     */
    @Override
    public List<PurchaseOrderVO> selectPurchaseOrderList(PurchaseOrder purchaseOrder) {
        List<PurchaseOrderVO> result = new ArrayList<PurchaseOrderVO>();
        if (purchaseOrder.getParams() != null) {
            if (purchaseOrder.getParams().containsKey("createTimeStart") && purchaseOrder.getParams().containsKey("createTimeEnd")) {
                if (purchaseOrder.getParams().get("createTimeStart") != null && !"".equals(purchaseOrder.getParams().get("createTimeStart"))
                        && purchaseOrder.getParams().get("createTimeEnd") != null && !"".equals(purchaseOrder.getParams().get("createTimeEnd"))) {
                    purchaseOrder.getParams().put("createTimeStart", purchaseOrder.getParams().get("createTimeStart") + " 00:00:00");
                    purchaseOrder.getParams().put("createTimeEnd", purchaseOrder.getParams().get("createTimeEnd") + " 23:59:59");
                }

            }
        }
        purchaseOrderMapper.selectPurchaseOrderList(purchaseOrder).forEach(item -> {
            result.add(convertPurchaseOrder(item));
        });
        return result;
    }

    private PurchaseOrderVO convertPurchaseOrder(PurchaseOrder purchaseOrder) {
        PurchaseOrderVO vo = new PurchaseOrderVO();
        BeanUtils.copyProperties(purchaseOrder, vo);
        if (purchaseOrder.getSupplierId() != null && purchaseOrder.getSupplierId() > 0) {
            MaterialSupplier materialSupplier = materialSupplierMapper.selectMaterialSupplierById(purchaseOrder.getSupplierId());
            if (materialSupplier != null) {
                vo.setSupplierName(materialSupplier.getName());
            }
        }
        vo.setTypeName(PurchaseConstants.TypeEnum.getTypeNameByValue(vo.getType().getTypeValue()));
        vo.setStatusName(PurchaseConstants.StatusEnum.getTypeNameByValue(vo.getStatus().getTypeValue()));
        vo.setWarehouseStatusName(PurchaseConstants.WarehouseStatusEnum.getTypeNameByValue(vo.getWarehouseStatus().getTypeValue()));
        return vo;
    }

    /**
     * 新增采购单
     *
     * @param purchaseOrder 采购单
     * @return 结果
     */
    @Override
    public int insertPurchaseOrder(PurchaseOrder purchaseOrder) {
        purchaseOrder.setCreateTime(DateUtils.getNowDate());
        purchaseOrder.setId(Long.valueOf(DateUtils.parseDateToStr("yyyyMMddHHmmss", new Date()) + String.valueOf(ThreadLocalRandom.current().nextInt(1000, 9999))));
        if (purchaseOrder.getParams().get("products") == null) {
            throw new ServiceException("采购单未新增食品");
        }
        int i = purchaseOrderMapper.insertPurchaseOrder(purchaseOrder);
        if (i > 0) {
            Map<String, Object> params = new HashMap<String, Object>(1);
            List<PurchaseOrderProduct> products = JSON.parseArray(JSON.toJSONString(purchaseOrder.getParams().get("products")), PurchaseOrderProduct.class);
            products.forEach(item -> {
                item.setOrderId(purchaseOrder.getId());
            });
            params.put("products", products);
            purchaseOrderProductMapper.insertPurchaseOrderProductBatch(params);
        }
        return i;
    }

    /**
     * 修改采购单
     *
     * @param purchaseOrder 采购单
     * @return 结果
     */
    @Override
    @Transactional
    public int updatePurchaseOrder(PurchaseOrder purchaseOrder) {
        purchaseOrder.setUpdateTime(DateUtils.getNowDate());
        int i = purchaseOrderMapper.updatePurchaseOrder(purchaseOrder);
        if (i > 0) {
            List<PurchaseOrderProduct> products = JSON.parseArray(JSON.toJSONString(purchaseOrder.getParams().get("products")), PurchaseOrderProduct.class);
            List<PurchaseOrderProduct> addList = new ArrayList<>(10);
            List<PurchaseOrderProduct> updateList = new ArrayList<>(10);
            products.forEach(item -> {
                if (item.getId() != null) {
                    updateList.add(item);
                } else {
                    item.setOrderId(purchaseOrder.getId());
                    addList.add(item);
                }
            });
            products.clear();

            if (!addList.isEmpty()) {
                //新增物品关联
                purchaseOrderProductMapper.insertPurchaseOrderProductBatch(new HashMap<String, Object>(1) {{
                    put("products", addList);
                }});
            }


            if (!updateList.isEmpty()) {
                //修改物品关联
                updateList.forEach(item -> {
                    purchaseOrderProductMapper.updatePurchaseOrderProduct(item);
                });
            }


        }
        return i;
    }

    /**
     * 批量删除采购单
     *
     * @param ids 需要删除的采购单主键
     * @return 结果
     */
    @Override
    public int deletePurchaseOrderByIds(Long[] ids) {
        int i = purchaseOrderMapper.deletePurchaseOrderByIds(ids);
        purchaseOrderProductMapper.deletePurchaseOrderProductByOrderIds(ids);
        return i;
    }

    /**
     * 删除采购单信息
     *
     * @param id 采购单主键
     * @return 结果
     */
    @Override
    public int deletePurchaseOrderById(Long id) {
        return purchaseOrderMapper.deletePurchaseOrderById(id);
    }
}
